package com.truthbean.jeetb.model.sys.repository;

import com.truthbean.jeetb.model.sys.entity.User;
import com.truthbean.jeetb.model.sys.repository.model.UserModel;
import java.util.*;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 * Created by truth on 16-9-6.
 */

public class UserRepository {
    @PersistenceUnit
    private EntityManagerFactory emf;

    private EntityManager em = emf.createEntityManager();

    @Resource
    private UserTransaction utx;

    private CriteriaBuilder builder;

    @PostConstruct
    private void init(){
        builder = em.getCriteriaBuilder();
    }

    public void insert(User user){
        try {
            utx.begin();
            em.persist(user);
            utx.commit();
        }catch (Exception e){
            try {
                utx.rollback();
            } catch (SystemException e1) {
                e1.printStackTrace();
            }
        }
    }

    public void update(User user){
        try {
            utx.begin();
            em.merge(user);
            utx.commit();
        }catch (Exception e){
            try {
                utx.rollback();
            } catch (SystemException e1) {
                e1.printStackTrace();
            }
        }
    }

    void delete(int id){
        try {
            utx.begin();
            em.remove(id);
            utx.commit();
        }catch (Exception e){
            try {
                utx.rollback();
            } catch (SystemException e1) {
                e1.printStackTrace();
            }
        }
    }

    public User findOne(int id) {
        return em.find(User.class, id);
    }

//    fun findByGroupPaged(group: String, begin: Int, size: Int): MutableList<User> {
//        val listCriteria = builder.createQuery(User::class.java)
//        val listRoot = listCriteria.from(User::class.java)
//        listCriteria.where(builder.equal(listRoot.get(UserModel.group), group))
//        listCriteria.select(listRoot)
//        val query = em.createQuery(listCriteria)
//        query.maxResults = size
//        query.firstResult = begin
//        return query.resultList
//    }

    public List<User> findAllPaged(int begin, int size) {
        CriteriaQuery<User> criteriaQuery = builder.createQuery(User.class);
        Root<User> root = criteriaQuery.from(User.class);

        criteriaQuery.select(root);

        TypedQuery<User> typedQuery = em.createQuery(criteriaQuery);

        typedQuery.setMaxResults(size);
        typedQuery.setFirstResult(begin);
        return typedQuery.getResultList();
    }
}